import { ISitemap, ISitemapItem, IBreadcrumbItem, IBreadcrumb } from '@/types';
import { replaceRouteSolidus } from '@/utils';

const menuUrl = '/menu.json';

export async function resolveMenu() {
	const config = Promise.all([fetchJson(menuUrl)]);
	return config;
}

const fetchJson = async (url: string) => {
	const res = await window.fetch(url).then((res) => res.json());
	return res;
};

export async function genNormalizeSiteMapNodes(sitemap: ISitemap) {
	const nodeMap: { [key: string]: IBreadcrumbItem } = {};

	sitemap.forEach(findBottomNode);

	bottomNodes.forEach((node: IBreadcrumbItem) => {
		const path = node.selectRule?.path as string;
		nodeMap[replaceRouteSolidus(path)] = node;
	});

	return nodeMap;
}

/**
 * 底层节点
 * 最底层菜单节点 自身和下钻页面 平铺
 */
const bottomNodes: IBreadcrumb = [];

/**
 * 底层节点，赋值parent数据
 */
function findBottomNode(sitemapItem: ISitemapItem) {
	const stack = [sitemapItem];

	while (stack.length) {
		const node = stack.pop() as ISitemapItem;
		if (hasChildren(node)) {
			if (node.selectRule?.path) {
				bottomNodes.push({
					...node,
					children: []
				});
			}

			node.children.forEach((child: IBreadcrumbItem) => {
				child.parent = {
					...node,
					children: []
				};
				if (hasChildren(child)) {
					if (child.childrenIsDrillPage) {
						bottomNodes.push(child);
					}
					stack.push(child);
				} else {
					bottomNodes.push({
						...child,
						isDrillPage: child.parent.childrenIsDrillPage
					});
				}
			});
		} else {
			bottomNodes.push(node);
		}
	}
}

function hasChildren(node: ISitemapItem) {
	return Array.isArray(node.children) && node.children.length;
}
